package com.example.musicapp.ui.recommend

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.musicapp.R
import com.example.musicapp.databinding.FragmentRecommendBinding
import com.example.musicapp.databinding.ItemGridSongBinding
import com.example.musicapp.model.Banner
import com.example.musicapp.model.Song
import com.example.musicapp.network.RetrofitClient
import com.example.musicapp.viewmodel.MusicViewModel
import kotlinx.coroutines.launch
import java.util.*
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

class RecommendFragment : Fragment() {
    private var _binding: FragmentRecommendBinding? = null
    private val binding get() = _binding!!
    private lateinit var bannerTimer: Timer
    private val bannerHandler = android.os.Handler(android.os.Looper.getMainLooper())
    private val viewModel: MusicViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRecommendBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fetchBanners()
        fetchRecommendedSongs()
    }

    private fun fetchBanners() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val bannerResponses = RetrofitClient.musicApi.getBanners()
                android.util.Log.d("RecommendFragment", "Banners received: $bannerResponses")
                
                val banners = bannerResponses.map { response ->
                    Banner(response.id, "Banner ${response.id}", response.bannerImgUrl)
                }
                setupBanner(banners)
            } catch (e: Exception) {
                android.util.Log.e("RecommendFragment", "Error fetching banners", e)
                e.printStackTrace()
            }
        }
    }

    private fun setupBanner(banners: List<Banner>) {
        binding.bannerViewPager.apply {
            adapter = BannerAdapter(banners)
            orientation = ViewPager2.ORIENTATION_HORIZONTAL

            // 自动轮播
            bannerTimer = Timer()
            bannerTimer.schedule(object : TimerTask() {
                override fun run() {
                    bannerHandler.post {
                        val nextItem = (currentItem + 1) % banners.size
                        setCurrentItem(nextItem, true)
                    }
                }
            }, 3000, 3000)
        }
    }

    private fun fetchRecommendedSongs() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val recommendResponses = RetrofitClient.musicApi.getRecommendedSongs()
                
                val songs = recommendResponses.map { response ->
                    Song(
                        id = response.id,
                        title = response.name,
                        artist = "",
                        album = "",
                        coverUrl = response.recImgUrl,
                        duration = when(response.id) {
                            1 -> 253  // 甜蜜蜜
                            2 -> 224  // 小城故事
                            3 -> 271  // 雨蝶
                            4 -> 242  // 风中的承诺
                            else -> response.duration ?: 180
                        }
                    )
                }
                setupRecommendedSongs(songs)
            } catch (e: Exception) {
                android.util.Log.e("RecommendFragment", "Error fetching recommended songs", e)
                e.printStackTrace()
            }
        }
    }

    private fun setupRecommendedSongs(songs: List<Song>) {
        binding.recommendedSongsRecyclerView.apply {
            layoutManager = GridLayoutManager(context, 3)
            adapter = RecommendedSongsAdapter(songs, viewModel::playSong)
        }
    }

    private fun getMockBanners(): List<Banner> {
        return listOf(
            Banner(1, "Banner 1", "https://example.com/banner1.jpg"),
            Banner(2, "Banner 2", "https://example.com/banner2.jpg"),
            Banner(3, "Banner 3", "https://example.com/banner3.jpg")
        )
    }

    private fun getMockSongs(): List<Song> {
        return listOf(
            Song(
                id = 1,
                title = "歌曲1",
                artist = "歌手1",
                album = "专辑1",
                coverUrl = "https://example.com/cover1.jpg",
                duration = 180
            ),
            Song(
                id = 2,
                title = "歌曲2",
                artist = "歌手2",
                album = "专辑2",
                coverUrl = "https://example.com/cover2.jpg",
                duration = 180
            ),
            Song(
                id = 3,
                title = "歌曲3",
                artist = "歌手3",
                album = "专辑3",
                coverUrl = "https://example.com/cover3.jpg",
                duration = 180
            )
        )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        bannerTimer.cancel()
        _binding = null
    }
} 